<?php
class ManageProductImagesController extends Controller {

	public $backend_left_menu = "application.modules.products.views.admin_menu._left_menu";
	public $backend_left_menu_datas = array('list'	=>	array());
	//public $backend_left_menu_datas = false;
	private $_model;
	public $layout='//layouts/main';
	public $categoryTitle=false;
	public $pageTitle="Manage images of a product";
	
	public function init()
	{
			Yii::app()->theme = 'backend';
			parent::init();
	}

	public function actionView($id) {
		$this->categoryTitle = $this->pageTitle;
		$this->pageTitle = 'View an image of a product';
		$this->render('view', array(
			'model' => $this->loadModel($id, 'ProductImage')
		));
	}
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	//public function actionUpdate($product_id, $id)
	public function actionUpdate($id)
	{
		//$baseScriptUrl = Yii::app()->assetManager->publish(dirname(__FILE__) . '/../assets/products');
		//Yii::app()->getClientScript()->registerCssFile($baseScriptUrl.'/css/products.css');

		$model = $this->loadModel($id);
		
		$product_id = $model->product_id;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['ProductImage'])) {
			//$model->attributes = $_POST['ProductImage'];
			$model->setAttributes($_POST['ProductImage']);
			
			$fileUpload = CUploadedFile::getInstance($model, 'image');
			if (isset($fileUpload)) {
				$uploadPath = YiiBase::getPathOfAlias('webroot') . Yii::app()->controller->module->product_image['url'];
			
				if (!is_dir($uploadPath))
					mkdir($uploadPath,0777,true);
					
				// Delete old image
				if ($model->image) {
					if (is_file($uploadPath .  $model->image)) 	unlink($uploadPath . $model->image);
					//unlink($uploadPath . '/lager_' . $model->image);
					if (is_file($uploadPath . 'thumbs/' . $model->image))		unlink($uploadPath . 'thumbs/' . $model->image);
				}
					
				//$filename = $model->alias . '.' . $fileUpload->getExtensionName(); //time() . mt_rand(0, 0xfff) . '.' . $fileUpload->getExtensionName();
				$filename = time() . mt_rand(0, 0xfff) . '.' . $fileUpload->getExtensionName();
				$fileUpload->saveAs($uploadPath . $filename);
					
				//Create lager and thumbnail image
				Yii::import('ext.phpthumb.EasyPhpThumb');

				// lager image
				$lagers = new EasyPhpThumb();
				$lagers->init();
				$lagers->setThumbsDirectory($uploadPath);
				$lagers->load($uploadPath . $filename)
					   ->resize(Yii::app()->controller->module->image['lager']['width'],
								Yii::app()->controller->module->image['lager']['height']
						)
					   ->save($filename);

				// thumbnails image
				$thumbs = new EasyPhpThumb();
				$thumbs->setThumbsDirectory($uploadPath.'thumbs/');
				$thumbs->load($uploadPath . $filename)
					   ->resize(Yii::app()->controller->module->image['thumbnail']['width'],
								Yii::app()->controller->module->image['thumbnail']['height']
						)
					   ->save($filename);
					
				$model->image = $filename;
			}
			if ($model->save())
				$this->redirect(Yii::app()->createUrl("/products/ManageProductImages/admin", array('product_id'=>$product_id)));
		}
		$this->categoryTitle = $this->pageTitle;
		$this->pageTitle = 'Edit an image of a product';
		$this->render('update', array(
            'model' => $model,
		));
	}

	public function actionCreate($product_id)
	{
        $model = new ProductImage;
		if (isset($_POST['ProductImage'])) {
			//$model->attributes = $_POST['ProductImage'];
			$model->setAttributes($_POST['ProductImage']);
			$model->product_id = $product_id;
			$model->validate();
			
        	if(!$model->hasErrors()){
				$fileUpload = CUploadedFile::getInstance($model, 'image');
				if (isset($fileUpload)) {
					$uploadPath = YiiBase::getPathOfAlias('webroot') . Yii::app()->controller->module->product_image['url'];
				
					if (!is_dir($uploadPath))
						mkdir($uploadPath,0777,true);
					
					$filename = time() . mt_rand(0, 0xfff) . '.' . $fileUpload->getExtensionName();
					$fileUpload->saveAs($uploadPath . $filename);
						
					//Create lager and thumbnail image
					Yii::import('ext.phpthumb.EasyPhpThumb');

					// lager image
					$lagers = new EasyPhpThumb();
					$lagers->init();
					$lagers->setThumbsDirectory($uploadPath);
					$lagers->load($uploadPath . $filename)
						   ->resize(Yii::app()->controller->module->image['lager']['width'],
									Yii::app()->controller->module->image['lager']['height']
							)
						   ->save($filename);

					// thumbnails image
					$thumbs = new EasyPhpThumb();
					$thumbs->setThumbsDirectory($uploadPath.'thumbs/');
					$thumbs->load($uploadPath . $filename)
						   ->resize(Yii::app()->controller->module->image['thumbnail']['width'],
									Yii::app()->controller->module->image['thumbnail']['height']
							)
						   ->save($filename);
						
					$model->image = $filename;
				}
				if ($model->save())
					$this->redirect(Yii::app()->createUrl("/products/ManageProductImages/admin", array('product_id'=>$product_id)));
			}
		}
		$this->categoryTitle = $this->pageTitle;
		$this->pageTitle = 'Create an image of a product';
		$this->render('create', array(
            'model' => $model,
		));
	}
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	//public function actionDelete($product_id, $id)
	public function actionDelete($id)
	{
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$model = $this->loadModel($id);
			
			//$model->product_id = $product_id;
			
			// X�a khoi db
			if ($model->delete()) 
			{
				// X�a image
				$uploadPath = YiiBase::getPathOfAlias('webroot') . '/wwwroot/upload_files/product_images/';
				$filename = $uploadPath . $model->image;
				if (is_file($filename)) @unlink($filename);
				$filenameThumb = $uploadPath . 'thumbs/' . $model->image;
				if (is_file($filenameThumb)) @unlink($filenameThumb);
			}

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
		throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin($product_id = null)
	{
		$baseScriptUrl = Yii::app()->assetManager->publish(dirname(__FILE__) . '/../assets/products');
		Yii::app()->getClientScript()->registerCssFile($baseScriptUrl.'/css/products.css');
		//Yii::app()->getClientScript()->registerCssFile($baseScriptUrl.'/css/jqtransform.css');
		//Yii::app()->getClientScript()->registerScriptFile($baseScriptUrl.'/js/jquery.jqtransform.js');
		Yii::app()->getClientScript()->registerScriptFile($baseScriptUrl.'/js/products.js');
		if (isset($_POST['products-image-grid_c0'])) {
			foreach ($_POST['products-image-grid_c0'] as $ID)
			{
				$model = $this->loadModel($ID);
				
				$model->product_id = $product_id;

				// Xoa khoi db
				if ($model->delete() == 'true')
				{
					// X�a image
					$uploadPath = YiiBase::getPathOfAlias('webroot') . '/wwwroot/upload_files/product_images/';
					$filename = $uploadPath . '/' . $model->image;
					if (is_file($filename)) @unlink($filename);
					$filenameThumb = $uploadPath . '/thumbs/' . $model->image;
					if (is_file($filenameThumb)) @unlink($filenameThumb);
				}
			}
		}
		$model = new ProductImage('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['ProductImage']))
		$model->attributes = $_GET['ProductImage'];
		$model->product_id = $product_id;
		
		/*
		$model = new CActiveDataProvider('ProductImage', array(
				'criteria' => array(
						'condition' => 'product_id = :product_id',
						'params' => array(':product_id' => $product_id),
						'order' => 'created DESC, priority ASC',
				),
				'pagination'=>array(
					'pageSize'=>Yii::app()->controller->module->entriesAlbumShowGrid
        ),
		));
		*/
		$this->render('admin', array(
			'model' => $model,
			'pageTitle' => 'Manage images of a product',
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model = ProductImage::model()->findByPk($id);
		if ($model === null)
		throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'products-image-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}